import {createSlice,configureStore} from '@reduxjs/toolkit'

//创建商品模块
const goodsSlice = createSlice({
    name:'goods',
    initialState:{
        goodsList:[]
    },
    reducers:{
        addGoods(state,{type,payload}){
            state.goodsList.unshift({
                id:Math.random().toString(36).slice(2),
                ...payload
            })
        }
    }
})

//创建购物车模块
const cartSlice = createSlice({
    name:'cart',
    initialState:{
        cartList:[]
    },
    reducers:{
        addCart(state,{type,payload}){
            console.log('121',payload)
            const index = state.cartList.findIndex(v=>v.id===payload.id)
            if(index>-1){
                state.cartList[index].buyNum+=1
            }else{
                state.cartList.unshift({...payload,buyNum:1})
            }
        }
    }
})

//创建仓库
const store = configureStore({
    reducer:{
        goods:goodsSlice.reducer,
        cart:cartSlice.reducer
    }
})

//订阅
const unSubscribe = store.subscribe(()=>{
    console.log(store.getState())
})

//修改数据
const { addGoods } = goodsSlice.actions
store.dispatch(addGoods({goodsName:'电脑',goodsPrice:1000}))

//添加购物车
const { addCart } = cartSlice.actions
const target = store.getState().goods.goodsList[0]
store.dispatch(addCart(target))
store.dispatch(addCart(target))
